﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Data.Linq;

using System.Configuration;
using System.Configuration.Provider;
using MyDHServer.DataAccess;
using MyDHServer.Compontents;
using MyDHServer.Compontents.DataProvider;
namespace MyDHServer.DataProvider.SqlDataProvider
{
    public class SqlBlogDataProvider:BlogDataProvider
    {
        private string _applicationName;
        public string ConnectonString { get; set; }



        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentException("config");

            if (String.IsNullOrEmpty(name))
                name = "SqlBlogDataProvider";

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "SQL Blog provider");
            }

            base.Initialize(name, config);

            _applicationName = config["applicationName"];
            if (string.IsNullOrEmpty(_applicationName))
                _applicationName = "/";

            string strconn = config["connectionStringName"];

            if (string.IsNullOrEmpty(strconn))
                throw new ProviderException ("Empty or missing connectionStringName");


            config.Remove("connectionStringName");

            if (ConfigurationManager.ConnectionStrings[strconn] == null)
                throw new ProviderException("Missing connection string");
            this.ConnectonString = ConfigurationManager.ConnectionStrings[strconn].ConnectionString;

            if (String.IsNullOrEmpty(this.ConnectonString))
                throw new ProviderException("Empty connection string");

        }

        public override void AddBlog(DHBlog blog)
        {
            DataBaseHelper.Insert<DHBlog>(blog);
        }

        public override void UpdateBlog(DHBlog blog)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override void DeleteBlog(int id)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override List<DHBlog> GetBlogs()
        {
            //List<DHBlog> bgs = new List<DHBlog>();
            var db = new MyDHServerDataContext(ConnectonString);

            List<DHBlog> blogs = (from blog in db.DHBlogs
                                  orderby blog.pubdate descending
                                  select blog).ToList();

            //foreach (DHBlog bg in blogs)
            //{
            //    bgs.Add(bg);
            //}

            return blogs;
        }
    }
}
